# -*- coding: UTF-8 -*-
"""
    @Author:YTQ
    @Time: 2023/4/27 15:19
    Description:
    虎牙直播专用的 base64
"""
import re

KEY_STR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='


def hy_decode(content):
    """
    虎牙 base64 解码
    :return:
    """
    fm_str = re.sub('[^A-Za-z0-9+/=]', '', content)
    t = ''
    f = 0
    while f < len(fm_str):
        s = KEY_STR.index(fm_str[f])
        f += 1
        o = KEY_STR.index(fm_str[f])
        f += 1
        u = KEY_STR.index(fm_str[f])
        f += 1
        a = KEY_STR.index(fm_str[f])
        f += 1
        #
        n = s << 2 | o >> 4
        r = (o & 15) << 4 | u >> 2
        i = (u & 3) << 6 | a
        t += str(chr(n))
        if u != 64:
            t += str(chr(r))
        if a != 64:
            t += str(chr(i))
    return hy_utf8_decode(t)


def hy_utf8_decode(content):
    """
    utf8 解码
    :return:
    """
    t = ''
    n = 0
    while n < len(content):
        r = ord(content[n])
        if r < 128:
            t += chr(r)
            n += 1
        elif r > 191 & r < 224:
            c2 = ord(content[n + 1])
            t += chr((r & 31) << 6 | c2 & 63)
            n += 2
        else:
            c2 = ord(content[n + 1])
            c3 = ord(content[n + 2])
            t += chr((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63)
            n += 3
    #
    return t



